﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleLambdaExpressions
{
  class Program
  {
    static void Main(string[] args)
    {
      Console.WriteLine("***** Fun with Lambdas *****\n");
      TraditionalDelegateSyntax();
      AnonymousMethodSyntax();
      
      Console.WriteLine();
      LambdaExpressionSyntax();

      Console.ReadLine();
    }

    #region Traditional delegate syntax
    static void TraditionalDelegateSyntax()
    {
      // Make a list of integers.
      List<int> list = new List<int>();
      list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });

      // Call FindAll() using traditional delegate syntax.
      Predicate<int> callback = new Predicate<int>(IsEvenNumber);
      List<int> evenNumbers = list.FindAll(callback);

      Console.WriteLine("Here are your even numbers:");
      foreach (int evenNumber in evenNumbers)
      {
        Console.Write("{0}\t", evenNumber);
      }
      Console.WriteLine();
    }
    // Target for the Predicate<> delegate.
    static bool IsEvenNumber(int i)
    {
      // Is it an even number?
      return (i % 2) == 0;
    }
    #endregion 

    #region Anonymous method syntax
    static void AnonymousMethodSyntax()
    {
      // Make a list of integers using C# 3.0
      // collection initialization syntax. 
      List<int> list = new List<int>();
      list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });

      List<int> evenNumbers = list.FindAll(
        delegate(int i)
        {
          return (i % 2) == 0;
        }
      );

      Console.WriteLine("Here are your even numbers:");
      foreach (int evenNumber in evenNumbers)
      {
        Console.Write("{0}\t", evenNumber);
      }
      Console.WriteLine();
    }
    #endregion

    #region Lambda expression syntax
    static void LambdaExpressionSyntax()
    {
      // Make a list of integers. 
      List<int> list = new List<int>();   
      list.AddRange(new int[] { 20, 1, 4, 8, 9, 44 });

      // Now process each argument within a group of 
      // code statements.
      List<int> evenNumbers = list.FindAll((i) => 
      { 
        Console.WriteLine("value of i is currently: {0}", i);
        bool isEven = ((i % 2) == 0);
        return isEven;
      });

      Console.WriteLine("Here are your even numbers:");
      foreach (int evenNumber in evenNumbers)
      {
        Console.Write("{0}\t", evenNumber);
      }
      Console.WriteLine();
    }
    #endregion
  }
}


